/*

Copyright (c) 2021 唐佐林
WeChat : delphi_tang
EMail: delphi_tang@dt4sw.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/
#ifndef IPCMESSAGE_H
#define IPCMESSAGE_H

#include <QObject>
#include <QByteArray>

class IPCMessage : public QObject
{
    struct MsgHeader
    {
        ushort type;
        ushort cmd;
        ushort index;
        ushort total;
        unsigned int length;

        MsgHeader()
        {
            type = 0;
            cmd = 0;
            index = 0;
            total = 0;
            length = 0;
        }
    };

    MsgHeader m_header;
    QByteArray m_payload;

    static bool TryMake(MsgHeader& header, const QByteArray& ba);
public:
    enum
    {
        MINSIZE = sizeof(MsgHeader)
    };

    IPCMessage(QObject* parent = NULL);
    IPCMessage(ushort type, ushort cmd, ushort index, ushort total, const char* payload = NULL, int length = 0, QObject* parent = NULL);
    IPCMessage(ushort type, ushort cmd, ushort index, ushort total, const QByteArray& payload, QObject* parent = NULL);

    ushort type() const;
    ushort cmd() const;
    ushort index() const;
    ushort total() const;
    bool setPayload(const char* payload, int length);
    bool setPayload(const QByteArray& ba);
    bool valid() const;
    int length() const;
    int size() const;
    const QByteArray& payload() const;

    QByteArray serialize() const;
    bool unserialize(QByteArray ba);

    static bool TryMake(IPCMessage& msg, const QByteArray& ba);
    static bool TryMakePart(IPCMessage& msg, const QByteArray& ba);
};

#endif // IPCMESSAGE_H
